package com.mune.gulimall.order.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class RabbitConfig {

  @Autowired
  RabbitTemplate rabbitTemplate;

  @Bean
  public MessageConverter messageConverter() {
    return new Jackson2JsonMessageConverter();
  }
  @PostConstruct
  public void initRabbit() {
    // 确认回调（P->B成功后执行）
    rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
      /**
       * 只要消息抵达Broker就ack=true
       * @param correlationData 当前消息唯一关联数据（唯一ID）
       * @param ack 消息是否成功收到
       * @param cause 失败的原因
       */
      @Override
      public void confirm(CorrelationData correlationData, boolean ack, String cause) {

      }
    });
    // 消息抵达队列回调
    rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
      /**
       * 只要消息没有投递到指定的队列，则会执行该回调
       * @param message 投递失败的消息，详细信息
       * @param replyCode 回复的状态码
       * @param replyText 回复的消息
       * @param exchange 消息所投递的交换机
       * @param routingKey 消息的路由键
       */
      @Override
      public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {

      }
    });
  }
}
